<template>
  <v-card flat class="pl-4">
    <div class="d-flex align-center title-container">
      <h3 class="pl-3 pr-3">Entity</h3>
      <v-btn
        depressed
        min-width="unset"
        height="40"
        width="40"
        color="#D9D9D9"
        class="rounded-circle"
        @click="$emit('routerBack')"
      >
        <v-icon color="#626C84">mdi-arrow-left-thick</v-icon>
      </v-btn>
    </div>
    <div class="list rounded-lg">
      <div
        class="d-flex justify-space-between pl-3 pr-3 align-center list-title"
      >
        <h3>Address</h3>
        <div>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openDeleteAddress(selectedAddress)"
                v-on="on"
                class="pointer mr-4"
                color="#BABABC"
                size="18"
              >
                mdi-delete
              </v-icon>
            </template>
            Delete Address
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openEditAddress(selectedAddress)"
                v-on="on"
                class="pointer mr-4"
                color="#BABABC"
                size="18"
              >
                mdi-square-edit-outline
              </v-icon>
            </template>
            Edit Address
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                v-on="on"
                @click="openAddAddress"
                class="pointer"
                color="#BABABC"
                size="18"
              >
                mdi-plus-thick
              </v-icon>
            </template>
            Add Address
          </v-tooltip>
        </div>
      </div>
      <v-treeview
        :items="addressList"
        :active="[activeAddress]"
        item-key="id"
        active-class="active"
        expand-icon="mdi-chevron-down"
      >
        <template #label="{ item }">
          <div
            class="pointer"
            :class="{
              active: selectedAddress && selectedAddress.id === item.id,
            }"
            @click="selectAddress(item)"
          >
            <h3>{{ item.locationCode }}</h3>
            <p class="ma-0">{{ item.address }}</p>
          </div>
        </template>
      </v-treeview>
    </div>
    <Dialog
      v-model="showDialog"
      :title="dialogTitle"
      :show-save="step !== 3"
      :width="dialogWidth"
      @submit="saveAddress"
    >
      <template>
        <AddEditAddress
          v-if="[1, 2].includes(step)"
          ref="addEditAddress"
        ></AddEditAddress>
        <Delete
          v-else
          @delete="deleteAddress(selectedAddress)"
          ref="deleteAddress"
          :title="deleteTitle"
          :subtitle="deleteSubtitle"
        ></Delete>
      </template>
    </Dialog>
  </v-card>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import { IAddress } from "@/components/Customer/index";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import AddEditAddress from "@/components/Customer/Dialog/Address/AddEditAddress.vue";
import Delete from "@/components/Customer/Dialog/Delete/Delete.vue";
@Component({
  components: {
    Dialog,
    AddEditAddress,
    Delete,
  },
})
export default class Address extends Vue {
  // 1.addAddress 2.editAddress 3.deleteAddress
  step = -1;
  // Dialog
  dialogTitle = "";
  showDialog = false;
  get dialogWidth() {
    return this.step === 3 ? 480 : 584;
  }
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // Address
  get activeAddress() {
    if (this.selectedAddress) {
      return this.selectedAddress.id;
    }
    return null;
  }
  get selectedAddress() {
    return this.$store.state.ContactInfoStore.selectedAddress;
  }
  set selectedAddress(item: IAddress | null) {
    this.$store.commit("ContactInfoStore/setSelectedAddress", item);
    if (!item) {
      this.$store.commit("ContactInfoStore/setContactInfo", null);
    }
  }
  get addressList() {
    return this.$store.state.ContactInfoStore.address;
  }
  @Watch("addressList", { immediate: true })
  onAddressListChange() {
    if (!this.selectedAddress && this.addressList && this.addressList.length) {
      this.selectAddress(this.addressList[0]);
    }
  }
  createdInitContactInfo() {
    return {
      setting: {
        id: "",
        projectName: "",
        priority: "",
        projectType: "",
        projectLocation: "",
        projectDescription: "",
        items: [],
      },
      items: {
        id: "",
        type: "",
        address: "",
        items: [],
      },
      contactPersons: [],
      contracts: [],
    };
  }
  selectAddress(item: IAddress) {
    if (!this.selectedAddress || this.selectedAddress.id !== item.id) {
      this.$store.commit("ContactInfoStore/setSelectedAddress", item);
      this.$store.commit("ContactInfoStore/setContactInfo", item.contactInfo);
    } else {
      this.$store.commit("ContactInfoStore/setSelectedAddress", null);
      this.$store.commit("ContactInfoStore/setContactInfo", null);
    }
  }

  // Action
  openAddAddress() {
    this.step = 1;
    this.dialogTitle = "Add Address";
    this.$nextTick(() => {
      (this.$refs.addEditAddress as AddEditAddress).resetForm();
    });
    this.openDialog();
  }
  openEditAddress(address: IAddress | null) {
    if (!address) {
      this.SweetAlertService.warning(
        "Please select the address you want to edit"
      );
      return;
    }
    this.step = 2;
    this.dialogTitle = "Edit Address";
    this.$nextTick(() => {
      const addEditAddressRef = this.$refs.addEditAddress as AddEditAddress;
      addEditAddressRef.resetForm();
      setTimeout(() => {
        addEditAddressRef.setFormData(address);
      });
    });
    this.openDialog();
  }
  deleteTitle = "Are you sure to delete this address?";
  get deleteSubtitle() {
    if (this.selectedAddress) {
      return `${this.selectedAddress.locationCode} - ${this.selectedAddress.address}`;
    } else {
      return "";
    }
  }
  openDeleteAddress(address: IAddress | null) {
    if (!address) {
      this.SweetAlertService.warning(
        "Please select the address you want to delete"
      );
      return;
    }
    this.step = 3;
    this.dialogTitle = "Delete";
    this.openDialog();
  }
  async saveAddress() {
    const addEditAddressRef = this.$refs.addEditAddress as AddEditAddress;
    const result = await addEditAddressRef.validateFormData();
    if (result) {
      if (this.step === 1) {
        result.id = String(new Date().getTime());
        if (this.selectedAddress) {
          this.addAddress(result as IAddress, this.selectedAddress);
        } else {
          this.addAddress(result as IAddress, this.addressList);
        }
      } else {
        this.editAddress(result as IAddress);
      }
      this.closeDialog();
    }
  }
  addAddress(address: IAddress, parent: IAddress | IAddress[] | undefined) {
    address.contactInfo = this.createdInitContactInfo();
    if (parent) {
      if (Array.isArray(parent)) {
        parent.push(address);
      } else {
        if (parent.children) {
          parent.children.push(address);
        } else {
          this.$set(parent, "children", [address]);
        }
      }
    } else {
      this.addressList.push(address);
    }
    this.selectAddress(address);
  }
  editAddress(address: IAddress) {
    if (!this.selectedAddress) {
      return;
    }
    Object.assign(this.selectedAddress, address);
  }
  deleteAddress(address: IAddress | null) {
    if (!address) {
      return;
    }
    let index = this.addressList.indexOf(address);
    if (index < 0) {
      const parent = this.getParent(this.addressList, address.id as string);
      if (parent) {
        const children = parent.children as IAddress[];
        index = children.indexOf(address);
        children.splice(index, 1);
      }
    } else {
      this.addressList.splice(index, 1);
    }
    this.selectedAddress = null;
    this.closeDialog();
  }
  // 获取父级元素
  getParent(treeItems: IAddress[], childrenId: string): IAddress | undefined {
    for (let i = 0; i < treeItems.length; i++) {
      const treeItem = treeItems[i];
      if (treeItem.children && treeItem.children.length !== 0) {
        if (
          treeItem.children.some((child) => {
            return child.id === childrenId;
          })
        ) {
          return treeItem;
        } else {
          const parent = this.getParent(treeItem.children, childrenId);
          if (parent) {
            return parent;
          }
        }
      }
    }
    return undefined;
  }

  destroyed() {
    this.$store.commit("ContactInfoStore/setSelectedAddress", null);
    this.$store.commit("ContactInfoStore/setContactInfo", null);
  }
}
</script>

<style lang="scss" scoped>
@import "@/components/Customer/ContactInfo/Address.scss";
</style>
